package com.b2c.erp.controller;

import com.b2c.entity.result.PagingResponse;
import com.b2c.entity.DataRow;
import com.b2c.entity.erp.ErpGoodsSpecEntity;
import com.b2c.erp.DataConfigObject;
import com.b2c.entity.ErpStockLocationEntity;
import com.b2c.erp.req.InvoiceDeleteReq;
import com.b2c.erp.response.ApiResult;
import com.b2c.entity.vo.ErpGoodsStockLogsListVo;
import com.b2c.entity.erp.vo.ErpGoodsSpecStockVo;
import com.b2c.entity.enums.EnumUserActionType;
import com.b2c.interfaces.wms.ErpGoodsStockInfoService;
import com.b2c.interfaces.erp.ErpUserActionLogService;
import com.b2c.interfaces.wms.StockLocationService;
import com.b2c.interfaces.wms.StockService;

import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 描述：
 * 库存查询Controller
 *
 * @author ly
 * @date 2019-03-26 9:16
 */
@RequestMapping("/stock")
@Controller
public class StockSearchController {
    @Autowired
    private StockService stockService;
    @Autowired
    private StockLocationService stockLocationService;
    @Autowired
    private ErpGoodsStockInfoService goodsStockInfoService;
    @Autowired
    private ErpUserActionLogService logService;


    /**
     * 仓位库存查询列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/stock_search", method = RequestMethod.GET)
    public String stockSearch(Model model, HttpServletRequest request) {
        String page = request.getParameter("page");
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();
        Integer houseId = 0;  //仓库
        String locationNum = "";

        if (!StringUtils.isEmpty(page)) {
            pageIndex = Integer.parseInt(page);
        }
        if (!StringUtils.isEmpty(request.getParameter("house"))) {
            houseId = Integer.parseInt(request.getParameter("house"));
        }
        if (!StringUtils.isEmpty(request.getParameter("str"))) {
            locationNum = request.getParameter("str");
        }

        model.addAttribute("locationNum", locationNum);


        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        PagingResponse<ErpGoodsSpecStockVo> result = stockService.goodsStockInfoSearch(pageIndex, pageSize, locationNum, houseId);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());



        model.addAttribute("houses", stockLocationService.getListByParentId(0));
        model.addAttribute("houseId", houseId);

        model.addAttribute("view", "spec_stock_search");
        model.addAttribute("pView", "sj");
        model.addAttribute("ejcd", "仓库");
        model.addAttribute("sjcd", "仓位库存查询");


        return "stock_stock_search";
    }


    /**
     * 仓位清空（仓位库存为0的）
     *
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/stock_search_clean_up", method = RequestMethod.POST)
    public ApiResult<Integer> getCheckout(@RequestBody InvoiceDeleteReq req, HttpServletRequest request) {

        Long stockInfoId = Long.valueOf(req.getId());

        var detail = goodsStockInfoService.getById(stockInfoId);
        if (detail == null) return new ApiResult<>(404, "数据不存在");
        else if (detail.getIsDelete().intValue() != 0) return new ApiResult<>(405, "该数据已删除");
        else if (detail.getCurrentQty().longValue() > 0) return new ApiResult<>(406, "还有库存，不允许删除");

        //更新数据为删除状态
        goodsStockInfoService.updateDeleteById(stockInfoId);

        Integer userId = Integer.parseInt(request.getSession().getAttribute("userId").toString());

        logService.addUserAction(userId, EnumUserActionType.Modify,
                "/stock/stock_search_clean_up?id=" + stockInfoId,
                "腾空仓位：仓位" + detail.getLocationId() + "SKU：" + detail.getSpecNumber(), "成功");

        return new ApiResult<>(0, "SUCCESS");
    }

    /**
     * SKU库存查询列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/spec_search", method = RequestMethod.GET)
    public String specStockSearch(Model model, HttpServletRequest request) {
        String page = request.getParameter("page");
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();

        if (!StringUtils.isEmpty(page)) {
            pageIndex = Integer.parseInt(page);
        }
        String number = "";
        if (!StringUtils.isEmpty(request.getParameter("number"))) {
            number = request.getParameter("number");
            model.addAttribute("number",number);
        }
        Integer categoryId = 0;
        if (!StringUtils.isEmpty(request.getParameter("categoryId"))) {
            categoryId = Integer.parseInt(request.getParameter("categoryId"));
            model.addAttribute("categoryId",categoryId);
        }


        int filter0 = 0;
        if (!StringUtils.isEmpty(request.getParameter("filter0"))) {
            filter0 = Integer.parseInt(request.getParameter("filter0"));
        }
        model.addAttribute("filter0",filter0);

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        PagingResponse<ErpGoodsSpecStockVo> result = stockService.goodsSkuSearch(pageIndex, pageSize, number,filter0,categoryId);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());
        model.addAttribute("totalQty", result.getData2());


        model.addAttribute("view", "spec_stock_search");
        model.addAttribute("pView", "sj");
        model.addAttribute("ejcd", "仓库");
        model.addAttribute("sjcd", "商品SKU库存查询");
        return "stock_spec_search";
    }

    /**
     * SKU库存查询列表记录
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/spec_search_logs", method = RequestMethod.GET)
    public String specStockSearchLogs(Model model, HttpServletRequest request) {
        String page = request.getParameter("page");
        Integer pageIndex = 1, pageSize = DataConfigObject.getInstance().getPageSize();

        if (!StringUtils.isEmpty(page)) {
            pageIndex = Integer.parseInt(page);
        }
        String number = "";
        if (!StringUtils.isEmpty(request.getParameter("number"))) {
            number = request.getParameter("number");
            model.addAttribute("number",number);
        }

        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        PagingResponse<ErpGoodsStockLogsListVo> result = stockService.goodsSkuSearchLogs(pageIndex, pageSize, number);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

        return "stock_spec_search_logs";
    }

    /**
     * 库存批次详情
     * @param model
     * @param specId
     * @param request
     * @return
     */
    @RequestMapping(value = "/stock_info_item", method = RequestMethod.GET)
    public String specStockInfoItem(Model model,@RequestParam Integer specId, HttpServletRequest request) {
       
    
        var list = goodsStockInfoService.getStockInfoItemListBySpecId(specId);
        model.addAttribute("totalSize", list.size());
        model.addAttribute("lists", list);

        return "stock_spec_search_info_item";
    }

    /**
     * 分配仓位
     * @param model
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/stock_location_apportion", method = RequestMethod.POST)
    public ApiResult<Integer> stockLocationApportion(@RequestBody DataRow model, HttpServletRequest request) {
        Integer id = Integer.parseInt(model.getString("id"));
        String number = model.getString("number");
       if(StringUtils.isEmpty(number))
           return new ApiResult<>(501, "参数错误：缺少number");


        ErpStockLocationEntity stockLocation = stockLocationService.getEntityByNumber(number);
        if(stockLocation == null)  return new ApiResult<>(501, "参数错误：仓位不存在");
        else if(stockLocation.getIsDelete() != 0)  return new ApiResult<>(501, "参数错误：仓位已经被删除");

        //检查是否被使用
        boolean used = stockLocationService.checkStockLocationUsed(stockLocation.getId());
        if(used) return new ApiResult<>(501, "参数错误：仓位已经被使用");


        //开始更新仓位
        goodsStockInfoService.apportionStockLocationForSpec(id,stockLocation.getId());

        return new ApiResult<>(0, "SUCCESS");
    }

    @ResponseBody
    @RequestMapping(value = "/spec_stock_info_export", method = RequestMethod.GET)
    public void purchasePutDetail(Model model, HttpServletRequest req, HttpServletResponse response) {

//        PagingResponse<ErpGoodsSpecStockVo> result = stockService.goodsSkuSearch(pageIndex, pageSize, number,filter0,categoryId);
        var lists = stockService.specStockByExport();//invoiceService.invoiceItemPOList();

        /***************根据店铺查询订单导出的信息*****************/
        String fileName = "spec_stock_info_export_";//excel文件名前缀
        //创建Excel工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();

        //创建Excel工作表对象
        HSSFSheet sheet = workbook.createSheet();
        HSSFRow row = null;
        HSSFCell cell = null;
        //第一行为空
        row = sheet.createRow(0);
        cell = row.createCell(0);
        cell.setCellValue("");
        cell = row.createCell(0);
        cell.setCellValue("商品编码");
        cell = row.createCell(1);
        cell.setCellValue("规格编码");
        cell = row.createCell(2);
        cell.setCellValue("规格属性");
        cell = row.createCell(3);
        cell.setCellValue("当前库存");
        cell = row.createCell(4);
        cell.setCellValue("采购价");


        int currRowNum = 0;
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 循环写入数据
        for (int i = 0; i < lists.size(); i++) {
            currRowNum++;
            //写入订单
            ErpGoodsSpecEntity itemVo = lists.get(i);
            //创建行
            row = sheet.createRow(currRowNum);
            cell = row.createCell(0);
            cell.setCellValue(itemVo.getGoodsNumber());
            //商品名称
            cell = row.createCell(1);
            cell.setCellValue(itemVo.getSpecNumber());
            cell = row.createCell(2);
            cell.setCellValue(itemVo.getColorValue()+itemVo.getSizeValue());

            cell = row.createCell(3);
            cell.setCellValue(itemVo.getCurrentQty());
            //退货单号
            cell = row.createCell(4);
            cell.setCellValue(String.format("%.2f",itemVo.getAmount()/itemVo.getCurrentQty()));
        }
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
            SimpleDateFormat newsdf = new SimpleDateFormat("yyyyMMdd");
            String date = newsdf.format(new Date());
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + new String((fileName + date + ".xls").getBytes("GBK"),
                    "ISO8859_1") + "\"");
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            out.flush();
            out.close();
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "导出失败!");
            e.printStackTrace();
        }
    }



}
